package org.xdj.blue.java.aio.client;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

public class AsynClient implements CompletionHandler<Void, AsynClient>, Runnable {
	
	private  AsynchronousSocketChannel client;
	private String ip;
	private int port;
	private CountDownLatch latch;
	
	public AsynClient(String ip,int port) {
		this.ip = ip;
		this.port = port;
		try {
			client = AsynchronousSocketChannel.open();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		System.out.println("--"+Thread.currentThread().getName()+"--");
		latch = new CountDownLatch(1);
		System.out.println("--请求访问"+port+"--");
		client.connect(new InetSocketAddress("localhost", port), this, this);
		
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		try {
			client.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void completed(Void result, AsynClient attachment) {
		System.out.println("--"+Thread.currentThread().getName()+"--");
		System.out.println("--客户端准备发送请求--");
		byte[] req = "i coming from client".getBytes();
		ByteBuffer byteBuffer = ByteBuffer.allocate(req.length);
		byteBuffer.put(req);
		byteBuffer.flip();
		client.write(byteBuffer, byteBuffer, new CompletionHandler<Integer, ByteBuffer>() {

			public void completed(Integer result, ByteBuffer attachment) {
				System.out.println("--"+Thread.currentThread().getName()+"--");
				if(attachment.hasRemaining()){
					System.out.println("--再次写入--");
					client.write(attachment, attachment, this);
				}else{
					System.out.println("--准备读取--");
					ByteBuffer readBuffer = ByteBuffer.allocate(1024);
					client.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>(){

						public void completed(Integer result,
								ByteBuffer attachment) {
							System.out.println("--"+Thread.currentThread().getName()+"--");
							attachment.flip();
							byte[] bytes = new byte[attachment.remaining()];
							attachment.get(bytes);
							String resp =null;
							try {
								resp = new String(bytes,"utf-8");
							} catch (UnsupportedEncodingException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							System.out.println("--响应："+resp);
							latch.countDown();
						}

						public void failed(Throwable exc, ByteBuffer attachment) {
							// TODO Auto-generated method stub
							try {
								client.close();
								latch.countDown();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}
						
					});
				}
				
			}

			public void failed(Throwable exc, ByteBuffer attachment) {
				// TODO Auto-generated method stub
				try {
					client.close();
					latch.countDown();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
	}

	public void failed(Throwable exc, AsynClient attachment) {
		// TODO Auto-generated method stub
		try {
			client.close();
			latch.countDown();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
